<!--
 * @Author: 赵宇
 * @Description: 
 * @Date: 2023-02-09 11:00:46
 * @LastEditTime: 2023-03-15 09:54:54
 * @LastEditors: zhao 13370229059@163.com
 * @FilePath: \pcj\src\page\home\components\sidebar.vue
-->
<template>
  <div class="sidebar">
    <p>我是logo</p>
    <el-menu class="sidebar-menu" router :default-active="menu.value" unique-opened ref="menuRef">
      <template v-for="(item, index) in menu.role">
        <template v-if="item.children && item.children.length">
          <el-sub-menu :index="index" :key="index">
            <template #title>
              <el-icon><component :is="item.icon" /></el-icon>
              <span>{{ item.label }}</span>
            </template>
            <el-menu-item :index="row.router" v-for="row in item.children" :key="'sub' + row.router">
              <template #title>
                <el-icon><component :is="row.icon" /></el-icon>
                <span>{{ row.label }}</span>
              </template>
            </el-menu-item>
          </el-sub-menu>
        </template>
        <template v-else>
          <el-menu-item :index="item.router" :key="index">
            <template #title>
              <el-icon><component :is="item.icon" /></el-icon>
              <span>{{ item.label }}</span>
            </template>
          </el-menu-item>
        </template>
      </template>
    </el-menu>
  </div>
</template>

<script setup>
import { role } from '@/config/data.js';
const route = useRoute();
let store = useStore();
let menuRef = ref('');
let menu = reactive({
  role: [],
  value: ''
});
const setMenuValue = () => {
  nextTick(() => {
    if (!menuRef.value) return;
    let path = route.meta.father || route.path;
    let index = menu.role.findIndex(r => (r.children ? r.children.find(n => n.router === path) : r.router === path));
    if (index === -1) return;
    // 只有当有子节点的时候，才需要打开
    if (menu.role[index].children) menuRef.value.open(index);
    menu.value = path;
  });
};
watch(
  () => route.path,
  val => {
    setMenuValue();
  },
  {
    immediate: true
  }
);
watch(
  () => store.state.commons.permissionIds,
  val => {
    if (!val) return;
    let arr = [];
    role.map(r => {
      // 如果没有子节点的话，直接看有没有勾选
      if (!r.children) {
        if (val.includes(r.id)) arr.push(r);
        return;
      }
      // 如果有子节点，只要有一个子菜单有权限，就要显示父节点菜单。再过滤掉没有权限的菜单
      if (r.children.map(n => val.includes(n.id * 100 + 1)).some(n => n)) {
        let row = { ...r };
        row.children = r.children.filter(n => val.includes(n.id * 100 + 1));
        arr.push(row);
      }
    });
    menu.role = arr;
    setMenuValue();
  },
  {
    immediate: true
  }
);
</script>
<style lang="scss" scoped>
.sidebar {
  width: 15%;
  min-width: 220px;
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-lighter);
  transition: all 1s;
  overflow-y: auto;
  &:hover {
    box-shadow: var(--el-box-shadow);
  }

  &-menu {
    border-right: 0;
  }
}
</style>
